package com.doradance.app.appactivity.search;


import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.donkingliang.labels.LabelsView;
import com.doradance.R;
import com.doradance.account.UrlCenter;
import com.doradance.account.utils.FragmentUtils;
import com.doradance.account.utils.ListDataSave;
import com.doradance.account.utils.MyGridView;
import com.doradance.common.http.MyHttpRequest;
import com.doradance.entity.HotHistoryEntity;
import com.doradance.entity.ShowSearchEntity;
import com.doradance.entity.clearListEntity;
import com.pachong.android.baseuicomponent.fragment.BaseFragment;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class SearchHomeFragment extends BaseFragment {


    @Bind(R.id.labels_search_history)
    LabelsView mLabelsSearchHistory;
    ListDataSave dataList;
    @Bind(R.id.gv_hot)
    MyGridView mGvHot;
    ArrayList<String> mArrayList = new ArrayList();
    @Bind(R.id.tv_no_history)
    TextView mTvNoHistory;

    public SearchHomeFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, view);
        dataList = new ListDataSave(getContext(), "searchhistory");
        for (int i = 0; i < dataList.getDataList("searchhistory").size(); i++) {
            mArrayList.add(dataList.getDataList("searchhistory").get(i).toString());
        }
        if(dataList.getDataList("searchhistory").size()==0){
            mTvNoHistory.setVisibility(View.VISIBLE);
            mLabelsSearchHistory.setVisibility(View.GONE);
        }
        initData();
        return view;
    }

    private void initData() {
        mLabelsSearchHistory.setSelectType(LabelsView.SelectType.NONE);
        ArrayList<String> testList = new ArrayList<>();
        dataList = new ListDataSave(getContext(), "searchhistory");
        for (int i = 0; i < dataList.getDataList("searchhistory").size(); i++) {
            testList.add(dataList.getDataList("searchhistory").get(i).toString());
        }
        //倒序
        Collections.reverse(testList);
        //获取去掉重复的元素的集合
        ArrayList newList = getArrayList(testList);
        mLabelsSearchHistory.setLabels(newList, new LabelsView.LabelTextProvider<String>() {
            @Override
            public CharSequence getLabelText(TextView label, int position, String data) {
                return data;
            }
        });
        mLabelsSearchHistory.setOnLabelClickListener(new LabelsView.OnLabelClickListener() {
            @Override
            public void onLabelClick(TextView label, Object data, int position) {
                mArrayList.add(label.getText().toString());
                dataList.setDataList("searchhistory", mArrayList);
                SearchVideoFragment searchVideoFragment = new SearchVideoFragment(label.getText().toString());
                FragmentUtils.replaceFragment(getFragmentManager(), R.id.fl_search, searchVideoFragment);
                EventBus.getDefault().post(new ShowSearchEntity(label.getText().toString()));
            }
        });
        initHotData();
    }

    ArrayList<String> item;

    private void initHotData() {
        item = new ArrayList<>();
        MyHttpRequest request = new MyHttpRequest(getContext());
        request.get(UrlCenter.HOTTAGS, null, new DataRequestListener<List<HotHistoryEntity>>(HotHistoryEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(List<HotHistoryEntity> o) {
                super.onSuccess(o);
                try{
                    for (int i = 0; i < o.size(); i++) {
                        item.add(o.get(i).getName());
                    }
                }catch(Exception e) {

                }
                HistoryAdapter historyAdapter = new HistoryAdapter();
                mGvHot.setAdapter(historyAdapter);
                mGvHot.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        mArrayList.add(item.get(position));
                        dataList.setDataList("searchhistory", mArrayList);
                        SearchVideoFragment searchVideoFragment = new SearchVideoFragment(item.get(position));
                        FragmentUtils.replaceFragment(getFragmentManager(), R.id.fl_search, searchVideoFragment);
                        EventBus.getDefault().post(new ShowSearchEntity(item.get(position)));
                    }
                });
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_search_home, container, false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    @OnClick(R.id.iv_delete_history)
    public void onViewClicked() {
        LayoutInflater factory = LayoutInflater.from(getContext());
        View inflate = factory.inflate(R.layout.no_member_dialog, null);
        TextView tvDialogTitle = (TextView) inflate.findViewById(R.id.tv_dialog_title);
        TextView tvBecomeVip = (TextView) inflate.findViewById(R.id.tv_become_vip);
        tvDialogTitle.setText(getString(R.string.clear_search));
        tvBecomeVip.setText(getString(R.string.confirm));
        final AlertDialog isMemberDialog = new AlertDialog.Builder(getContext())
                .setView(inflate).create();
        inflate.findViewById(R.id.tv_no_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isMemberDialog.cancel();
            }
        });
        inflate.findViewById(R.id.tv_become_vip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataList.clearDataList();
                mTvNoHistory.setVisibility(View.VISIBLE);
                mLabelsSearchHistory.setVisibility(View.GONE);
                EventBus.getDefault().post(new clearListEntity(false));
                isMemberDialog.cancel();
                initData();
            }
        });
        //设置点击Dialog外部任意区域关闭Dialog
        isMemberDialog.setCanceledOnTouchOutside(true);
        isMemberDialog.show();
    }


    public class HistoryAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return item.size();
        }

        @Override
        public Object getItem(int position) {
            return item.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(getContext(), R.layout.gv_history_item, null);
            }
            TextView tvHistoryItem = (TextView) convertView.findViewById(R.id.tv_history_item);
            tvHistoryItem.setText(item.get(position));
            return convertView;
        }

    }
    //去除重复元素
    public static ArrayList getArrayList(ArrayList list){
        ArrayList newList = new ArrayList();
        Iterator it = list.iterator();
        while(it.hasNext()){
            Object obj = it.next();
            if(!newList.contains(obj)){
                newList.add(obj);
            }
        }
        return newList;
    }
}
